﻿using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using Fluid.Values;

namespace ZYing.LiquidThemeEngine.Objects
{
    public class Template
    {
        private static readonly ConcurrentDictionary<string, FluidValue> Cache = new();

        private string _path;

        public Template(string path)
        {
            _path = path ?? throw new ArgumentNullException(nameof(path));
            var tmp = path.Split('/', '\\');
            if (tmp.Length == 1)
            {
                Name = StringValue.Create(tmp[0]);
                Directory = NilValue.Instance;
            }
            else
            {
                Name = StringValue.Create(tmp[tmp.Length - 1]);
                Directory = StringValue.Create(string.Join("/", tmp.Take(tmp.Length - 1)));
            }
        }

        public StringValue Name { get; }
        public FluidValue Directory { get; }

        public static FluidValue Get(String template)
        {
            var name = Helper.NormalTemplateName(template);
            return Cache.GetOrAdd(name, Create);
        }

        private static FluidValue Create(String template)
        {
            return new ObjectValue(new Template(template));
        }
        public override string ToString()
        {
            return _path;
        }
    }
}